/**
 * 生成二维码
 */

import { Modal, Image, Button, Form, Space, Input, message } from "antd";
import React, { FC, useEffect, useState } from "react";
import { ModuleOneBox, ModuleTwoBox } from "./style";
import { basicIp, saomaIp } from "../../../../../api/http";
import { DownloadOutlined } from "@ant-design/icons";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import { getGbSystemSetGetCodeId } from "../../api";
import { useWindowFontSize } from "../../../../../assets/fun/Antd/configprovider";

export interface IErweimaPrams {
  paramsArr: {
    paramsName: string; //参数名称
    paramsValue: string; // 参数值
  }[];
}

const GenerateQRCode: FC<{
  isModalOpen: boolean;
  handleCancel: () => void;
  id?: React.Key; //磅房ID
}> = ({ isModalOpen, handleCancel, id }) => {
  const [form] = Form.useForm<IErweimaPrams>();
  const imageWidth = useWindowFontSize(120);
  const [urlData, setUrlData] = useState("");
  const [process, setProcess] = useState(1); // 1 填写参数 2 生成二维码

  useEffect(() => {
    (async () => {
      if (id) {
        const { code, msg, data } = (await getGbSystemSetGetCodeId({
          id,
        })) as {
          code: number;
          msg: string;
          data?: string;
        };
        if (code === 20000) {
          if (data) {
            // 获取参数
            const params = data.split("$$");

            params.shift();
            console.log(params);
            // 分解参数
            const paramsArr = params.map((item) => {
              const [paramsName, paramsValue] = item.split("=");
              return {
                paramsName,
                paramsValue,
              };
            });
            form.setFieldsValue({
              paramsArr: [...paramsArr],
            });
          }
        } else {
          message.error(msg);
        }
      }
    })();

    return () => {};
  }, [form, id]);

  const handleDownload = () => {
    fetch(urlData)
      .then((response) => response.blob()) // 将图片地址转换为 Blob
      .then((blob) => {
        const link = document.createElement("a"); // 创建一个 <a> 元素
        const url = window.URL.createObjectURL(blob); // 创建一个临时 URL
        link.href = url; // 设置链接的 href 为 Blob 的 URL
        link.download = "二维码.png"; // 设置下载文件的默认名称
        document.body.appendChild(link); // 将 <a> 元素添加到 DOM 中
        link.click(); // 触发点击事件
        document.body.removeChild(link); // 下载完成后移除 <a> 元素
        window.URL.revokeObjectURL(url); // 释放 URL 对象
      })
      .catch((err) => {
        console.error("下载失败:", err);
      });
  };
  // 点击生成二维码
  const handleClickCreate = async () => {
    const values = await form.validateFields();
    if (id) {
      console.log(
        values.paramsArr
          .map((item) => `${item.paramsName}=${item.paramsValue}`)
          .join("$$")
      );
      const url =
        saomaIp +
        "?params=id=" +
        id +
        "$$" +
        values.paramsArr
          .map((item) => `${item.paramsName}=${item.paramsValue}`)
          .join("$$");
      console.log(url);
      setUrlData(`${basicIp}/gb-system-set/generateCode?id=${id}&url=${url}`);
      setProcess(2);
    }
  };
  const handleNeibuCancel = () => {
    form.resetFields();
    handleCancel();
    setUrlData("");
    setProcess(1);
  };

  const footerHtml = () => {
    if (process === 1) {
      return [
        <Button onClick={handleNeibuCancel}>取消</Button>,
        <Button type="primary" onClick={() => handleClickCreate()}>
          点击生成
        </Button>,
      ];
    } else {
      return [
        <Button type="primary" onClick={() => setProcess(1)}>
          上一步
        </Button>,
        <Button onClick={handleNeibuCancel}>关闭</Button>,
      ];
    }
  };

  return (
    <Modal
      title="生成称重链接二维码"
      closable={{ "aria-label": "Custom Close Button" }}
      open={isModalOpen}
      onCancel={handleNeibuCancel}
      footer={footerHtml()}
      width={useWindowFontSize(484)}
    >
      <>
        {process === 1 ? (
          <ModuleTwoBox>
            <Form form={form} name="dynamic_form_nest_item" autoComplete="off">
              <Form.List name="paramsArr">
                {(fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name, ...restField }) => (
                      <Space
                        key={key}
                        style={{ display: "flex", marginBottom: 8 }}
                        align="baseline"
                      >
                        <Form.Item
                          {...restField}
                          name={[name, "paramsName"]}
                          rules={[
                            { required: true, message: "请输入参数名称" },
                          ]}
                        >
                          <Input
                            placeholder="请输入参数名称"
                            style={{ width: "16.8rem" }}
                          />
                        </Form.Item>
                        <Form.Item
                          {...restField}
                          name={[name, "paramsValue"]}
                          rules={[{ required: true, message: "请输入参数值" }]}
                        >
                          <Input
                            placeholder="请输入参数值"
                            style={{ width: "16.8rem" }}
                          />
                        </Form.Item>
                        <MinusCircleOutlined onClick={() => remove(name)} />
                      </Space>
                    ))}
                    <Form.Item>
                      <Button
                        type="link"
                        onClick={() => add()}
                        block
                        icon={<PlusOutlined />}
                      >
                        增加一组
                      </Button>
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </Form>
          </ModuleTwoBox>
        ) : (
          <ModuleOneBox>
            <div className="waibao">
              <Image
                width={imageWidth}
                className="qrcode-img"
                src={urlData}
                alt="二维码"
              />

              <Button
                type="link"
                onClick={handleDownload}
                icon={<DownloadOutlined />}
              >
                保存二维码
              </Button>
            </div>
          </ModuleOneBox>
        )}
      </>
    </Modal>
  );
};

export default GenerateQRCode;
